package com.taxi.management.service.Impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.taxi.management.service.TokenService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component//托管给Spring
public class TokenServiceImpl implements TokenService {
    @Resource
    private  RedisTemplate<String,String> redisTemplate;//注入redis
    /**
     * 生成token
     * @param uname 用户名
     * @return String
     */
    @Override
    public String createToken(String uname) {
        String token = JWT.create().withAudience(uname).sign(Algorithm.HMAC256(uname));
        redisTemplate.opsForValue().set(uname,token,60*6, TimeUnit.MINUTES);//存入redis(有效期是360分钟)
        return token;
    }

    /**
     * 判定Token
     * @param uname 用户名
     * @param token token
     * @return boolean
     */
    @Override
    public boolean isToken(String uname, String token) {
        return redisTemplate.opsForValue().get(uname).equals(token);
    }

    /**
     * 退出登录的时候 删除redis中的key
     * @param uname uname
     * @return boolean
     */
    @Override
    public boolean delToken(String uname) {
        return redisTemplate.delete(uname);
    }


}
